package neichuan.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public abstract class Server implements Runnable{
    private int port;
    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;

    public Server(int port){
        this.port=port;
    }
    public Server(){

    }
    public void run(){
        bossGroup=new NioEventLoopGroup();
        workerGroup=new NioEventLoopGroup();
        try{
            ServerBootstrap sb=new ServerBootstrap();
            sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
            setChildHandler(sb);
            setOption(sb);
            setChildOption(sb);
            // Bind and start to accept incoming connections.
            ChannelFuture f = sb.bind(port).sync();

            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    protected abstract void setChildHandler(ServerBootstrap sb);

    protected void setOption(ServerBootstrap sb){
//        sb.option(ChannelOption.SO_BACKLOG, 128);
    }

    protected void setChildOption(ServerBootstrap sb){
//        sb.childOption(ChannelOption.SO_KEEPALIVE, true);
    }

    public void close(){
        if(workerGroup!=null){
            workerGroup.shutdownGracefully();
        }
        if(bossGroup!=null){
            bossGroup.shutdownGracefully();
        }
    }


}
